package com.fruit.auth.dao.impl;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Repository;

import com.fruit.auth.dao.RoleDao;
import com.fruit.auth.dao.RolePrivilegeDao;
import com.fruit.auth.dao.UserRoleDao;
import com.fruit.auth.model.Role;
import com.fruit.auth.model.User;
import com.fruit.dao.impl.BaseDaoImpl;

@Repository("roleDao")
public class RoleDaoImpl extends BaseDaoImpl<Role> implements RoleDao
{
	@Resource(name="rolePrivilegeDao")
	private RolePrivilegeDao rolePrivilegeDao;
	
	@Resource(name="userRoleDao")
	private UserRoleDao userRoleDao;
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> findRoleUsers(Serializable roleId)
	{
		String hql="select ur.user from UserRole ur where ur.role.id=?";
		return getSession().createQuery(hql).setParameter(1, roleId).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Integer> findRoleUserIds(Serializable roleId)
	{
		String hql="select ur.user.id from UserRole ur where ur.role.id=?";
		return getSession().createQuery(hql).setParameter(1, roleId).list();
	}

	public void saveRolePrivileges(final List<Integer> roleIds,final List<Integer> privilegeIds)
	{
		final String sql="insert into auth_role_privilege(AUTH_ROLE_id,AUTH_PRIVILEGE_id) values(?,?)";
		getSession().doWork(new Work()
		{
			
			@Override
			public void execute(Connection connection) throws SQLException
			{
				connection.setAutoCommit(false);
				PreparedStatement stat=connection.prepareStatement(sql);
				for(int i=0;i<roleIds.size();i++)
				{
					stat.setInt(1, roleIds.get(i));
					stat.setInt(2, privilegeIds.get(i));
					stat.addBatch();
				}
				stat.executeBatch();
				connection.commit();
			}
		});
	}
	
	public void deleteRole(Role role)
	{
		rolePrivilegeDao.unAuthRolePrivileges(role);
		userRoleDao.unAuthRoleUsers(role);
		batchEntityByHql("delete from Role where id=?", role.getId());
	}
	
	public void deleteRoles(String roleIdsStr)
	{
		rolePrivilegeDao.unAuthRolesPrivileges(roleIdsStr);
		userRoleDao.unAuthRolesUsers(roleIdsStr);
		
		StringBuilder deleteRolesSql=new StringBuilder();
		deleteRolesSql.append("delete from AUTH_ROLE where id in(");
		deleteRolesSql.append(roleIdsStr).append(")");
		executeUpdateSql(deleteRolesSql.toString());
	}
}
